//示例可变参数---开始
// <script src="https://lbs.sgmap.cn/maps?v=3.0.0"></script>
// <script src="https://map.epgis.com.cn/maps?v=3.0.0"></script>

//是否加载电网图
var loadPowerGrid = true

//电网图需要加载的图层（仅矢量栅格出图方式有效）
var layers = [300000,301000,100000,103000]
//电网图的过滤条件（仅矢量栅格出图方式有效）
var displayFilter = []
//矢量栅格图层参数
var gridLayerOptions = {}

//是否使用切片来加载电网
var isTile = false
//切片图层参数
var tileOptions = {}


//地图初始化参数
var mapOptions = {
    style: "aegis://styles/aegis/Streets",
    zoom: 10,//23,
    maxZoom: 23.5,
    center: [114.15501499771665, 30.582553617618018],//[116.89962187,24.97372043]
}

//选择工具参数
var selectToolOptions = {}
//捕捉工具参数
var snapToolOptions = {}

//示例可变参数---结束

//选择工具
var selectTool = null
//是否追加选择
var isAddOn = false

//捕捉工具
var snapTool = null
var snapedData = null
//地图实例
var map = null;
//矢量电网图层实例
var gridLayer = null;

//当前案例实际使用的出图服务地址
var mapServiceUrl = ''
//微服务加载完成标记
var msFlag = false
//思极地图加载完成标记
var sgMapFlag = false

//实例页面的回调方法
var pageCallBack = null
//是否添加专题图网格
var addGridCell = false
//专题图网格图层
var cellLayer = null

//调试用(无需调整)
var workerUrl = ''

/**
 * 动态加载JS
 * @param {String} url 脚本地址
 * @param {Function} callback  回调函数
 */
var dynamicLoadJs = function (url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    if (typeof (callback) == 'function') {
        script.onload = script.onreadystatechange = function () {
            if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                callback();
                script.onload = script.onreadystatechange = null;
            }
        };
        script.onerror = function (err) {
            alert('请在弹出页面确认安全问题后回来刷新本页面')
            window.open(url, '_blank')
        }
    }
    head.appendChild(script);
}

/**
 * 初始化网格图层
 */
function initCellLayer() {
    cellLayer = new egisV2.layer.GridCellLayer(
        {
            map: map,
            bounds: [[118.18995135082379, 24.47834215450987], [118.19061021844635, 24.478524030580136]],
            lineColor: '#fff',
            lineWidth: 1,
            lineOpacity: 0.3,
            backgroundColor: '#000000',
            backgroundOpacity: 1,
            cellSize: 1//单元格尺寸1代表实际跨度为0.000009度
        }
    )
    cellLayer.setVisible(false)
    cellLayer.render()

    // snapTool.addGridCell(cellLayer)
}

/**
 * 初始化思极地图
 */
function initMap() {
    if (!msFlag || !sgMapFlag) {
        return
    }

    map = egisV2.createMap({
            container: 'map',
            style: "aegis://styles/aegis/StreetsLight",

            // style: {
            //     glyphs: "aegis://fonts/aegis/{fontstack}/{range}.pbf",
            //     name: "浅色地图",
            //     sources: {
            //         epgis: {
            //             type: "vector",
            //             url: "aegis://aegis.Streets.20200601"
            //         }
            //     },
            //     layers: [
            //         {
            //             id: "background",
            //             layout: {
            //                 visibility: "visible"
            //             },
            //             paint: {
            //                 "background-color": "#000000"
            //             },
            //             type: "background"
            //         }
            //     ],
            //     sprite: "aegis://sprites/aegis/Streets",
            //     version: 8,
            // },
            doubleClickZoom: true,
            zoom: 10,
            preserveDrawingBuffer: true,
            maxZoom: 23.5,
            center: [114.15501499771665, 30.582553617618018],
            localIdeographFontFamily: 'Microsoft YoHei',
            ...mapOptions
        }
    )


    // map.scrollZoom.setWheelZoomRate(1)
    map.egis.selectionSet.setSpeed(5)
    map.on('load', e => {
        if (!map.style.stylesheet.glyphs) {
            map.style.stylesheet.glyphs = "aegis://fonts/aegis/{fontstack}/{range}.pbf"
            map.style.glyphManager.setURL("aegis://fonts/aegis/{fontstack}/{range}.pbf")
        }

        new SGMap.EleSymbolLayer({mobile: true, type: 'all'});//加载电网图数据
        map.addControl(new SGMap.ScaleControl({
            maxWidth: 80,
            unit: 'metric'
        }), 'bottom-left');
        if (addGridCell) {
            initCellLayer()
        }


        if (loadPowerGrid) {
            //是否通过切片加载数据
            if (isTile) {
                initGridTileLayer()
            } else {
                initGridLayer()
            }

        }

        if (pageCallBack) {
            pageCallBack()
        }
        setInfoBarData('ib_mapZoom', map.getZoom())
    })
    //这里是地图点击的测试代码
    map.on("click", function (e) {
        var features = map.queryRenderedFeatures(e.point);
        console.log(e.lngLat)
        console.log(features);
    });
    //
    map.on("zoomend", function (e) {
        console.log('比例尺:  1/', map.getScale())
        if (document.getElementById('ib_mapZoom')) {
            document.getElementById('ib_mapZoom').innerHTML = Number(map.getZoom()).toFixed(1)
        }
        console.log('层级:', map.getZoom())
    });

    initInfoBar()
}

/**
 * 初始化选择工具
 */
function initSelectTool() {
    selectTool = new egisV2.tool.SelectTool(
        map,
        {
            type: 'rectangle',//支持point，circle，rectangle，polygon
            borderWidth: 2,//绘制过程中的边框宽度
            borderColor: '#009ecc',//绘制过程中的边框颜色
            fillColor: '#009ecc',//绘制过程中的填充色
            fillOpacity: 0.5,//绘制过程中的填充透明度
            // layers: ['301000']//打开此选项，可以过滤被选中的目标图层
            selectedColor: '#ff00ff',
            isAddOn: isAddOn,
            // cursorStyle: 'crosshair',
            ...selectToolOptions
        })
    selectTool.on(egisV2.event.SelectEvent.DEVS_SELECTED, e => {
        console.log('当前选中的设备集合:' + selectTool._type)
        console.log(e)
    })
}

/**
 * 初始化捕捉工具
 */
function initSnapTool() {
    snapTool = new egisV2.tool.SnapTool(map, {

        // layers: ['3201000'],
        // types: ['terminal','line'],
        // priority: ['terminal','line'],
        // cursorStyle: 'crosshair',
        tolerance: 20,
        layers: null,
        // layers: [115000 ,110000 ,190000 ,201000 ,190000 ,110000 ,116000 ,140000 ,111000 ,3216000,102000 ,170000 ,112000 ,4106000,119000 ,113000 ,110000 ,160000 ,130000 ,118000 ,120000 ,180000 ,115000 ,114000 ,115000 ,190000 ,121000 ,8190000,102000 ,180000 ,202000],
        types: ['cellPoint', 'cellLine', 'point', 'line', 'terminal'],
        fillTypes: ['10300001'],
        // fillTypes:[],
        cursorStyle: 'crosshair',
        snapColors: {
            'point': '#00ffeb',
            'line': '#00ffeb',
            'terminal': '#ff0000',
            'cellLine': '#00ffeb',
            'cellPoint': '#00ffeb'
        },
        ...snapToolOptions
    })

    snapTool.on(egisV2.event.SnapEvent.DEV_SNAPPED, e => {
        if (e && e.geomType != 'cellLine' && e.geomType != 'cellPoint') {
            snapedData = e
            console.log(e.geomType)
            console.log(e)
        } else {
            snapedData = null
        }

    })
    map.on('click', e => {
        if (snapedData) {
            console.log('捕捉到的数据:-------------', new Date().getTime())
            console.log('SnapData:', snapedData)
            console.log('-------------------------')
        }
    })
    map.on('zoomend', e => {
        console.log('层级:' + map.getZoom())
        console.log('比例尺:1/' + map.getScale())
    })
}

/**
 * 微服务登录
 */
function msLogin() {
    post(msServiceUrl + '/authorityservice/login/integrate', {
        appkey: msKey
    }).then(
        res => {
            if (res.data.success) {
                // alert("登录成功！");
                //step-3:配置sdk对接微服务的参数
                //设置微服务出图参数是否全报文加密(设置true和false都可以，默认是false)
                // egisV2.MicroService.serviceInfo.encMode = false//这个是给sdk请求vecformat接口用的参数，vecformat为共享服务，现场无需使用全报文加密
                //设置微服务的token
                egisV2.MicroService.serviceInfo.token = res.data.resultValue.token;
                //设置微服务的secretKey
                egisV2.MicroService.serviceInfo.secretKey = msSecretKey
                msFlag = true
                initMap();
            } else {
                alert(res.data.message);
            }
        },
        err => {
            alert('微服务认证失败')

        }
    ).catch(e => {
        alert('微服务异常')
    })
}

/**
 * 初始化电网矢量切片图层
 */
function initGridTileLayer() {
    //按需隐藏建筑图层
    map.setLayoutProperty("Building", "visibility", "none");
    //创建切片图层
    gridTileLayer = new egisV2.layer.GridTileLayer({
        map: map,
        // layers:['300000','198812'],
        url: tileUrl,
        maxLevel: 18,
        tileSize: 512,
        cacheId: '',//缓存ID，默认图层自动生成
        ...tileOptions
    })
    let startTime = new Date().getTime()
    gridTileLayer.on('startLoadingData', e => {
        startTime = new Date().getTime()
        setInfoBarData('ib_gridTime', '加载中')
    })
    gridTileLayer.on('endLoadingData', e => {
        let during = new Date().getTime() - startTime
        setInfoBarData('ib_gridTime', Number(during / 1000).toFixed(2) + '秒')
    })

    gridTileLayer.on(egisV2.event.GridVectorLayerEvent.BEFORE_RENDER, e => {
        //请勿再次事件的回调方法内调用gridTileLayer的render方法，这么做会导致循环调用

        console.log('切片即将渲染' + new Date().getTime())
    })
    gridTileLayer.on(egisV2.event.GridVectorLayerEvent.AFTER_RENDER, e => {
        //请勿再次事件的回调方法内调用gridTileLayer的render方法，这么做会导致循环调用
        console.log('切片渲染完成' + new Date().getTime())
    })

    gridTileLayer.render()
}

/**
 * 初始化电网图层
 */
function initGridLayer() {
    //这个data参数中的各个属性与电网SDK的FeaturesLayer中的相关参数是一致的（即栅格服务的出图参数）
    gridLayer = new egisV2.layer.GridVectorLayer({
        map: map,//思极地图的map对象实例
        url: mapServiceUrl,//栅格出图服务地址
        workerUrl: workerUrl,
        method: mapServiceUrl == msServiceUrl + '/mapservice/mapexport/vecformat' ? 'POST' : 'GET',//直连使用get请求，微服务使用post请求
        data: {
            layers: layers.join(','),//要显示的图层
            displayfilter: displayFilter,//这个参数可以使用数组格式，如[{'300000':'dydj = 3'}],也可以将数组格式的数据通过JSON.stringify转成字符串，sdk这里有做兼容处理。
            mapid: 110,
            maptype: 1001,

            // FILTERFLYLINE: 1,//是否过滤飞线
            // FLYLINELENGTH: 2500 * 10,//判定为飞线的最小距离

            // disschema: 1,
            ...gridLayerOptions
        }
    })

    gridLayer.render();
    let startTime = new Date().getTime()
    gridLayer.on('startLoadingData', e => {
        startTime = new Date().getTime()
        setInfoBarData('ib_gridTime', '加载中')
    })
    gridLayer.on('endLoadingData', e => {
        let during = new Date().getTime() - startTime
        setInfoBarData('ib_gridTime', Number(during / 1000).toFixed(2) + '秒')
    })

    //渲染前
    gridLayer.on(egisV2.event.GridVectorLayerEvent.BEFORE_RENDER, e => {
        //每次请求到的电网数据可以在这里获取并供业务层使用
        //完成之后调用该方法执行渲染（即用户可以在渲染前随意修改数据）
        //渲染前调可以自行增删改数据
        // e.keys.splice(e.keys.indexOf('301000'),1)
        // e.keys.splice(e.keys.indexOf('301000_extend'),1)
        // delete e.data['301000']
        // delete e.data['301000_extend']
        //请勿再次事件的回调方法内调用gridVectorLayer的render方法，这么做会导致循环调用
        console.log('渲染开始:' + new Date().getTime())
    })

    gridLayer.on(egisV2.event.GridVectorLayerEvent.HANDLE_DEV, dev => {
        //请勿再次事件的回调方法内调用gridVectorLayer的render方法，这么做会导致循环调用
        //每个电网设备在叠加本地设备缓存之后，渲染之前会触发该回调，业务层可以在这里对属性进行对应判断，例如检测到了批次号就可以删除本地缓存
        // console.log(dev)
    })

    //渲染后
    gridLayer.on(egisV2.event.GridVectorLayerEvent.AFTER_RENDER, () => {
        console.log('渲染结束:' + new Date().getTime())
    })
    //渲染出错
    gridLayer.on(egisV2.event.GridVectorLayerEvent.ERROR_RENDER, err => {
        console.log('渲染出错:' + new Date().getTime())
    })
}

/**
 * 通过微服务加载电网图（现场适用）
 * @param callback
 */
function loadPowerGrid_microService(callback) {
    dynamicLoadJs(egisV2Url, () => {
        dynamicLoadJs(sgMapSdkUrl, () => {
            pageCallBack = callback
            egisV2.MicroService.active = true
            mapServiceUrl = msServiceUrl + '/mapservice/mapexport/vecformat'
            //思极地图鉴权
            SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function () {
                //,"SGMap.RoadNetLayer" 暂不支持这个插件
                SGMap.plugin(["SGMap.EleSymbolLayer"]).then(function (res) {
                    sgMapFlag = true
                    initMap();
                });
            });
            //微服务鉴权
            msLogin()
        })
    })
}

/**
 * 直连栅格服务(开发测试环境适用)
 * @param callback
 */
function loadPowerGrid_direct(callback) {
    dynamicLoadJs(egisV2Url, () => {
        dynamicLoadJs(sgMapSdkUrl, () => {
            pageCallBack = callback
            msFlag = true
            egisV2.MicroService.active = false
            mapServiceUrl = rasterMapServiceUrl
            SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function () {
                SGMap.plugin(["SGMap.EleSymbolLayer"]).then(function (res) {
                    sgMapFlag = true
                    initMap();
                });
            });
        })
    })


}

/**
 * 加载地理图（包含SGMap.EleSymbolLayer插件）
 * @param callback
 */
function loadGeoMap(callback) {
    dynamicLoadJs(egisV2Url, () => {
        dynamicLoadJs(sgMapSdkUrl, () => {
            pageCallBack = callback
            loadPowerGrid = false
            msFlag = true

            SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function () {
                SGMap.plugin(["SGMap.EleSymbolLayer"]).then(function (res) {
                    sgMapFlag = true
                    initMap();
                });
            });
        })
    })


}

/**
 * 加载地理图（包含微服务登录）
 * @param callback
 */
function loadGeoMap_ms(callback) {
    dynamicLoadJs(egisV2Url, () => {
        dynamicLoadJs(sgMapSdkUrl, () => {
            pageCallBack = callback
            loadPowerGrid = false
            SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function () {
                SGMap.plugin(["SGMap.EleSymbolLayer"]).then(function (res) {
                    sgMapFlag = true
                    initMap();
                });
            });
            msLogin()
        })
    })

}

/**
 * 加载电网矢量切片
 * @param callback
 */
function loadGeoMap_tile(callback) {
    dynamicLoadJs(egisV2Url, () => {
        dynamicLoadJs(sgMapSdkUrl, () => {
            pageCallBack = callback
            loadPowerGrid = false
            SGMap.tokenTask.login(sgMapKey, sgMapSn).then(function () {
                SGMap.plugin(["SGMap.EleSymbolLayer"]).then(function (res) {
                    sgMapFlag = true
                    initMap();
                });
            });
            msLogin()
        })
    })

}


function initInfoBar() {
    let infoBar = document.createElement('div')
    infoBar.classList.add('infoBar')
    document.body.appendChild(infoBar)
    document.querySelector('.infoBar').innerHTML = `<div>层级:<label id="ib_mapZoom">0</label></div><div>电网加载耗时:<label id="ib_gridTime">0</label></div>`
}

/**
 * 给状态栏的dom节点写数据
 * @param domId
 * @param text
 */
function setInfoBarData(domId, text) {
    if (document.getElementById(domId)) {
        document.getElementById(domId).innerHTML = text
    }
}

window.locateByLocation = function (center, zoom) {
    let dCenter = null
    let tmpPoint = null
    if (center instanceof Array) {
        tmpPoint = {x: center[0], y: center[1]}
    } else if (center.lng && center.lat) {
        tmpPoint = {x: center.lng, y: center.lat}
    }

    if (tmpPoint.x > 180 || tmpPoint.x < -180) {
        dCenter = egisV2.util.DataUtil.mercatorToDegree(tmpPoint)
    } else {
        dCenter = {lng: tmpPoint.x, lat: tmpPoint.y}
    }

    map.jumpTo({
        center: dCenter,
        zoom: zoom
    })


}
